import string
from random import random

from complex_PLM.PRNG import PRNG_Cplx_T


def differential_attack():
    plaintext = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=1000))
    key = random.random()  # 随机生成初始状态
    ciphertext = chaotic_cipher(plaintext, key)
    ciphertext = PRNG_Cplx_T(x0, y0, 64, 64, 2.5, 2.5, stream_len, is_int_s)

    # 枚举密钥空间进行差分分析
    key_space = [random.random() for _ in range(100)]
    result = []

    for possible_key in key_space:
        decrypted_text = chaotic_cipher(ciphertext, possible_key)
        diff = sum([1 for i in range(len(plaintext)) if plaintext[i] != decrypted_text[i]]) / len(plaintext)
        result.append((possible_key, diff))

    # 找到最小差异的密钥
    min_diff_key = min(result, key=lambda x: x[1])

    print("Original Key: ", key)
    print("Found Key: ", min_diff_key[0])

differential_attack()